import { _decorator, AudioSourceComponent, Component, Node } from 'cc';
import { gameConfig } from '../data/gameConfig';
import { loadRes } from './loadRes';
const { ccclass, property } = _decorator;

@ccclass('audioTool')
export class audioTool {
    private soundComp: AudioSourceComponent = null;
    private bgmComp: AudioSourceComponent = null;

    /**
     * 单例
     */
    private static _ins: audioTool = null;
    public static get ins() {
        if (!this._ins) {
            this._ins = new audioTool();
            this._ins.initAudio();
        }
        return this._ins;
    }
    /**
     * 初始化音频组件
     */
    private initAudio() {
        //用于单次播放的音效
        this.soundComp = new AudioSourceComponent();
        this.soundComp.loop = false;
        //循环播放背景音乐
        this.bgmComp = new AudioSourceComponent();
        this.bgmComp.loop = true;
    }
    /**
     * 停止背景音乐
     */
    public stopMusic() {
        this.bgmComp.stop();
    }
    /**
     * 设置音量
     */
    public setVolume(volume: number) {
        this.soundComp.volume = volume;
        this.bgmComp.volume = volume;
    }
    /**
     * 播放背景音乐
     *@@param audio 音乐名字
     */
    public async playMusic(audio: string) {
        //获取音源
        let music = await loadRes.ins.getClip(audio);
        //设置音量
        this.bgmComp.volume = gameConfig.bgmVol;
        //设置音源
        this.bgmComp.clip = music;
        this.bgmComp.play();
        console.log('播放背景音乐', audio);
    }

    /**
       * 播放一次性音效
       */
    public async playSound(audio: string) {
        let clip = await loadRes.ins.getClip(audio);
        this.soundComp.playOneShot(clip, gameConfig.bgmVol);
    }
}


